#encoding: utf-8
from .getLogs import collectLogs
from .runCase import runCase_single, runOneCase
import time,datetime
import traceback
from multiprocessing import Pool
import config
from .startDB import sparrowDB
import pymysql
from .commonFunc import generateNums
from .dingtalk import sendDingTalkMsg_sparrow, sendDingTalkWarnMsg_sparrow

# 定义程序运行方式（自行控制方式）
# def waysToRun(case, runCaseWay, runCaseWay_01, waitTime):
#     try:
#         # 循环运行
#         if runCaseWay == 0:
#             collectLogs(loginfo='sparrow自动化测试程序将在 3 秒后开始循环运行', lever='info', logger='waysToRun')
#             time.sleep(3)
#             start = time.time()
#             count = 0
#             if waitTime < 1:
#                 waitTime = 1
#             while 1:
#                 count += 1
#
#                 p = Pool(4)
#                 # for i in range(5):
#                 #     p.apply_async(long_time_task, args=(i,))
#                 # print('Waiting for all subprocesses done...')
#                 # p.close()
#                 # p.join()
#
#                 for item in case:
#                     try:
#                         runCase_single(case=item)
#                         # p.apply_async(runCase_single, args=(item,))
#                         # p.close()
#                         # p.join()
#                     except:
#                         collectLogs(loginfo='执行[%s]遇到异常，原因：%s' %(item,traceback.format_exc()), lever='error', logger='waysToRun')
#                 end = time.time()
#                 totalCostTime = int((end - start))
#                 if count % 30 == 0:
#                     collectLogs('程序已连续运行 %d 小时 %d 分钟' % (totalCostTime / 3600, (totalCostTime % 3600) / 60), lever='info', logger='waysToRun')
#                 collectLogs('%d 秒之后继续执行，等待中...' % (waitTime), logger='waysToRun')
#                 time.sleep(waitTime)
#
#         # 按指定次数执行
#         elif runCaseWay > 0 and runCaseWay_01 == '次':
#             collectLogs(loginfo='sparrow自动化测试程序即将开始，方式：执行 %d 次，间隔 %d 秒。' % (runCaseWay, waitTime),
#                         logger='waysToRun')
#
#         # 按指定分钟数执行
#         elif runCaseWay > 0 and runCaseWay_01 == '分钟':
#             collectLogs(loginfo='sparrow自动化测试程序即将开始，方式：执行 %d 分钟，间隔 %d 秒。' % (runCaseWay, waitTime),
#                         logger='waysToRun')
#
#         # 都不符合
#         else:
#             collectLogs(loginfo='参数设置有误！（case=%s，runCaseWay=%s，runCaseWay_01=%s，waitTime=%s）' %(str(case), str(runCaseWay), str(runCaseWay_01), str(waitTime)), logger='waysToRun')
#     except Exception:
#         collectLogs(loginfo='执行遇到异常，原因：%s' % traceback.format_exc(), lever='error', logger='waysToRun')


# 定义程序运行方式（走调度）
def waysToRun(case, runCaseWay, runCaseWay_01, waitTime, groupId, plan_id, plan_name):
    MAX_RES_LENTH = config.maxResponseLenth
    SEND_MAX_RES = config.sendMaxResponse
    DINGTALK_URL = config.DINGTALK_URL_SPARROW + config.ACCESS_TOKEN_SPARROW
    DINGTALK_URL_WARN = config.DINGTALK_URL_SPARROW + config.ACCESS_TOKEN_SPARROW_WARN
    summary = {"任务名称": plan_name, "用例总数": len(case), "成功用例": 0, "未执行":0, "失败用例": 0}
    s_plan_name = "'" + plan_name + "'"
    try:
        # 按调度执行
        if runCaseWay == 0:
            wheel_no = "'" + generateNums(32, 1) + "'"
            sql1 = "select * from case_run_res where wheel_no = %s" % (wheel_no,)
            check_wheel_no = sparrowDB.get_one(sql1)
            if check_wheel_no:
                wheel_no = "'" + generateNums(33, 1) + "'"
            countSuccess = 0
            countFailed = 0
            errorCasesMsgList = []
            overWarnTimeLimitList = []
            for item in case:
                errorCasesMsgList_tem = []
                overWarnTimeLimitList_tem = []
                curtime = "'" + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "'"
                user = "'" + '系统更新' + "'"
                try:
                    # res = runCase_single(case=item)
                    res = runOneCase(case=item)

                    response = response_send = res['data']['runRes']
                    if len(response) > MAX_RES_LENTH:
                        response = response[:MAX_RES_LENTH]
                    if len(response_send) > SEND_MAX_RES:
                        response_send = response_send[:SEND_MAX_RES]
                    response = "'" + pymysql.escape_string(response) + "'"
                    resPath = "'" + res['data']['casePath'] + "'"
                    resParam = "'" + pymysql.escape_string(res['data']['caseParam']) + "'"
                    expect_res = "'" + res['data']['expect_res'] + "'"
                    # case_sign = "'" + item.case_sign + "'"
                    case_sign = "'" + item[2] + "'"
                    case_header = "'" + item[7] + "'"
                    runCode = res['runCode']
                    httpCode = res['data']['httpCode']
                    duration = int(res['data']['duration'][:-2])
                    duration_sec = duration / 1000
                    if runCode == 1:
                        countSuccess += 1
                    if runCode == 9:
                        countFailed += 1
                        errorCasesMsgList_tem.append(item[1])
                        errorCasesMsgList_tem.append(item[0])
                        errorCasesMsgList_tem.append(item[6])
                        errorCasesMsgList_tem.append('<font color=#FF0000>失败</font>')
                        errorCasesMsgList_tem.append(httpCode)
                        errorCasesMsgList_tem.append(item[3])
                        errorCasesMsgList_tem.append(response_send)
                        errorCasesMsgList.append(errorCasesMsgList_tem)
                    if duration_sec >= config.MIN_LIMIT_WARNTIME_YELLOW:
                        duration_sec_color = '<font color=#FFD700>' + str(duration_sec) + '</font>'
                        overWarnTimeLimitList_tem.append(item[1])
                        overWarnTimeLimitList_tem.append(item[0])
                        if duration_sec >= config.MIN_LIMIT_WARNTIME_RED:
                            duration_sec_color = '<font color=#FF0000>' + str(duration_sec) + '</font>'
                        overWarnTimeLimitList_tem.append(duration_sec_color)
                        overWarnTimeLimitList_tem.append(item[3])
                        overWarnTimeLimitList.append(overWarnTimeLimitList_tem)
                except:
                    collectLogs(loginfo='执行[%s]遇到异常，原因：%s' % (item, traceback.format_exc()), lever='error',
                                logger='waysToRun')
                    response = "'" + '遇到异常，未执行' + "'"
                    resPath = "'" + '遇到异常，未执行' + "'"
                    resParam = "'" + '遇到异常，未执行' + "'"
                    expect_res = "'" + '遇到异常，未执行' + "'"

                try:
                    # 将结果插入数据库
                    # sql = '''INSERT INTO case_run_res(res_case_id,wheel_no,res_case_sign,res_group_id,res_case_path,res_case_parm,res_status,res_http_code,expect_res,res_detail,cost_time,run_type,create_by,update_by,create_at,update_at)
                    #          VALUES (%d,%s,%s,%d,%s,%s,%d,%d,%s,%s,%d,%d,%s,%s,%s,%s)''' % (item.case_id, wheel_no,case_sign, groupId, resPath, resParam, res['runCode'], res['data']['httpCode'], expect_res, response, int(res['data']['duration'][:-2]), 2, user, user, curtime, curtime)
                    sql = '''INSERT INTO case_run_res(res_case_id,wheel_no,res_case_sign,res_group_id,res_case_path,res_case_parm,res_status,res_http_code,expect_res,res_detail,cost_time,run_type,create_by,update_by,create_at,update_at,res_plan_id,res_case_header) 
                             VALUES (%d,%s,%s,%d,%s,%s,%d,%d,%s,%s,%d,%d,%s,%s,%s,%s,%d,%s)''' % (item[0], wheel_no, case_sign, groupId, resPath, resParam, runCode, httpCode, expect_res, response, duration, 1, user, user, curtime, curtime, plan_id, case_header)

                    db_res = sparrowDB.insert(sql)
                    if db_res:
                        collectLogs(loginfo='[%s]的执行结果插入数据库成功！' % (item,), lever='info', logger='waysToRun')
                    else:
                        temSql = '''INSERT INTO case_run_res(res_case_id,wheel_no,res_case_sign,res_group_id,res_case_path,res_case_parm,res_status,res_http_code,expect_res,res_detail,cost_time,run_type,create_by,update_by,create_at,update_at,res_plan_id,res_case_header) 
                                 VALUES (%d,%s,%s,%d,%s,%s,%d,%d,%s,%s,%d,%d,%s,%s,%s,%s,%d,%s)''' % (item[0], wheel_no, case_sign, groupId, resPath, resParam, runCode, httpCode, expect_res, '结果入库失败', duration, 1, user, user, curtime, curtime, plan_id, case_header)
                        temRes = sparrowDB.insert(temSql)
                        if temRes:
                            collectLogs(loginfo='[%s]的执行结果插入数据库成功，但是response入库失败' % (item, ), lever='info', logger='waysToRun')
                        else:
                            collectLogs(loginfo='[%s]的执行结果插入数据库失败，失败的insert语句：%s' % (item, sql), lever='warning', logger='waysToRun')
                except:
                    temSql2 = '''INSERT INTO case_run_res(res_case_id,wheel_no,res_case_sign,res_group_id,res_case_path,res_case_parm,res_status,res_http_code,expect_res,res_detail,cost_time,run_type,create_by,update_by,create_at,update_at,res_plan_id,res_case_header) 
                                 VALUES (%d,%s,%s,%d,%s,%s,%d,%d,%s,%s,%d,%d,%s,%s,%s,%s,%d,%s)''' % (item[0], wheel_no, case_sign, groupId, resPath, resParam, runCode, httpCode, expect_res, '结果入库异常', duration, 1, user, user, curtime, curtime, plan_id, case_header)
                    temRes2 = sparrowDB.insert(temSql2)
                    if temRes2:
                        collectLogs(loginfo='[%s]的执行结果插入数据库成功，但是response入库失败' % (item, ), lever='info', logger='waysToRun')
                    else:
                        collectLogs(loginfo='[%s]的执行结果插入数据库遇到异常，原因：%s' % (item, traceback.format_exc()), lever='error', logger='waysToRun')

            collectLogs(loginfo='本轮计划【%s】执行结束，%d秒后进行下次执行...' %(plan_name, waitTime), logger='waysToRun')

            # 结果统计数据处理
            summary['成功用例'] = countSuccess
            summary['未执行'] = summary['用例总数'] - countSuccess - countFailed
            summary['失败用例'] = countFailed

            # 执行结果统计入库
            summary_time = "'" + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "'"
            try:
                summary_sql = '''INSERT INTO case_run_res_summary(s_plan_id,s_plan_name,total_count,succ_count,fail_count,other_count,run_type,create_at) 
                                 VALUES (%d,%s,%d,%d,%d,%d,%d,%s)''' % (plan_id, s_plan_name, summary['用例总数'], summary['成功用例'], summary['失败用例'], summary['未执行'], 1, summary_time)
                db_res = sparrowDB.insert(summary_sql)
                if db_res:
                    collectLogs(loginfo='结果统计插入数据库成功！', lever='info', logger='waysToRun')
                else:
                    collectLogs(loginfo='结果统计插入数据库失败，插入结果为[%s]，失败的insert语句：%s' % (str(db_res), summary_sql), lever='info', logger='waysToRun')
            except:
                collectLogs(loginfo='结果统计插入数据库遇到异常，原因：%s' % (traceback.format_exc()), lever='error', logger='waysToRun')

            # 组装钉钉报警消息
            if config.isDingtalk and errorCasesMsgList:
                collectLogs(loginfo='有失败用例，需要发送消息提醒，开始发送钉钉报警消息...', logger='waysToRun')
                errorCaseMsg = ''
                for caseItem in errorCasesMsgList:
                    toCaseUrl = config.MESSAGE_URL_SPARROW + str(caseItem[1])
                    if caseItem[4] == 200:
                        httpCodeColor = '<font color=#32CD32>200</font>'
                    else:
                        httpCodeColor = '<font color=#FF0000>'+str(caseItem[4])+'</font>'
                    errorCaseMsg = errorCaseMsg + "【第" + str(errorCasesMsgList.index(caseItem) + 1) + "个】[" + caseItem[0] + "](" + toCaseUrl + ") \n> #### 预期结果：" + caseItem[2] + " \n> #### 匹配结果：" + caseItem[3] + "，httpCode：" + httpCodeColor + " \n> #### [" + caseItem[5] + "](" + caseItem[5] + ") \n> #### 响应信息：" + caseItem[6] + " \n\n> "
                sendRes = sendDingTalkMsg_sparrow(DINGTALK_URL, summary, errorCaseMsg)
                if sendRes["code"] == 1:
                    collectLogs(loginfo='钉钉报警消息发送成功！', logger='waysToRun')
                else:
                    collectLogs(loginfo='钉钉报警消息发送失败，发送响应：%s' % (sendRes,), lever='warning', logger='waysToRun')

            # 组装钉钉报警消息，响应时间超过阀值预警
            if config.IS_SEND_WARN_MSG and overWarnTimeLimitList:
                summaryMsg = "任务【" + plan_name + "】中有 " + str(len(overWarnTimeLimitList)) + " 个用例响应时间超过 " + str(config.MIN_LIMIT_WARNTIME_YELLOW) + " 秒，请及时确认服务是否正常，详细信息如下："
                warnCaseMsg = ''
                for warnItem in overWarnTimeLimitList:
                    toWarnCaseUrl = config.MESSAGE_URL_SPARROW + str(warnItem[1])
                    warnCaseMsg = warnCaseMsg + "【第" + str(overWarnTimeLimitList.index(warnItem) + 1) + "个】[" + warnItem[0] + "](" + toWarnCaseUrl + ") \n> #### 响应时间：" + warnItem[2] + " 秒 \n> #### URL：" + warnItem[3] + " \n\n> "
                sendWarnMsgRes = sendDingTalkWarnMsg_sparrow(DINGTALK_URL_WARN, summaryMsg, warnCaseMsg)
                if sendWarnMsgRes["code"] == 1:
                    collectLogs(loginfo='钉钉预警消息发送成功！', logger='waysToRun')
                else:
                    collectLogs(loginfo='钉钉预警消息发送失败，发送响应：%s' % (sendWarnMsgRes,), lever='warning', logger='waysToRun')

        # 按指定次数执行
        elif runCaseWay > 0 and runCaseWay_01 == '次':
            start = time.time()
            tem = runCaseWay
            while runCaseWay > 0:
                wheel_no = "'" + generateNums(32,1) + "'"
                sql1 = "select * from case_run_res where wheel_no = %s" %(wheel_no,)
                check_wheel_no = sparrowDB.get_one(sql1)
                if check_wheel_no:
                    wheel_no = "'" + generateNums(33, 1) + "'"

                countSuccess = 0
                countFailed = 0
                errorCasesMsgList = []
                overWarnTimeLimitList = []
                for item in case:
                    errorCasesMsgList_tem = []
                    overWarnTimeLimitList_tem = []
                    curtime = "'" + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "'"
                    user = "'" + '系统更新' + "'"
                    try:
                        # res = runCase_single(case=item)
                        res = runOneCase(case=item)

                        response = response_send = res['data']['runRes']
                        if len(response) > MAX_RES_LENTH:
                            response = response[:MAX_RES_LENTH]
                        if len(response_send) > SEND_MAX_RES:
                            response_send = response_send[:SEND_MAX_RES]
                        response = "'" + pymysql.escape_string(response) + "'"
                        resPath = "'" + res['data']['casePath'] + "'"
                        resParam = "'" + pymysql.escape_string(res['data']['caseParam']) + "'"
                        expect_res = "'" + res['data']['expect_res'] + "'"
                        case_sign = "'" + item[2] + "'"
                        case_header = "'" + item[7] + "'"
                        runCode = res['runCode']
                        httpCode = res['data']['httpCode']
                        duration = int(res['data']['duration'][:-2])
                        duration_sec = duration / 1000
                        if runCode == 1:
                            countSuccess += 1
                        if runCode == 9:
                            countFailed += 1
                            errorCasesMsgList_tem.append(item[1])
                            errorCasesMsgList_tem.append(item[0])
                            errorCasesMsgList_tem.append(item[6])
                            errorCasesMsgList_tem.append('<font color=#FF0000>失败</font>')
                            errorCasesMsgList_tem.append(httpCode)
                            errorCasesMsgList_tem.append(item[3])
                            errorCasesMsgList_tem.append(response_send)
                            errorCasesMsgList.append(errorCasesMsgList_tem)
                        if duration_sec >= config.MIN_LIMIT_WARNTIME_YELLOW:
                            duration_sec_color = '<font color=#FFD700>' + str(duration_sec) + '</font>'
                            overWarnTimeLimitList_tem.append(item[1])
                            overWarnTimeLimitList_tem.append(item[0])
                            if duration_sec >= config.MIN_LIMIT_WARNTIME_RED:
                                duration_sec_color = '<font color=#FF0000>'+str(duration_sec)+'</font>'
                            overWarnTimeLimitList_tem.append(duration_sec_color)
                            overWarnTimeLimitList_tem.append(item[3])
                            overWarnTimeLimitList.append(overWarnTimeLimitList_tem)
                    except:
                        collectLogs(loginfo='执行[%s]遇到异常，原因：%s' %(item,traceback.format_exc()), lever='error', logger='waysToRun')
                        response = "'" + '遇到异常，未执行' + "'"
                        resPath = "'" + '遇到异常，未执行' + "'"
                        resParam = "'" + '遇到异常，未执行' + "'"
                        expect_res = "'" + '遇到异常，未执行' + "'"
                    try:
                        # 将结果插入数据库
                        sql = '''INSERT INTO case_run_res(res_case_id,wheel_no,res_case_sign,res_group_id,res_case_path,res_case_parm,res_status,res_http_code,expect_res,res_detail,cost_time,run_type,create_by,update_by,create_at,update_at,res_plan_id,res_case_header) 
                                 VALUES (%d,%s,%s,%d,%s,%s,%d,%d,%s,%s,%d,%d,%s,%s,%s,%s,%d,%s)''' % (item[0], wheel_no,case_sign, groupId, resPath, resParam, runCode, httpCode, expect_res, response, duration, 2, user, user, curtime, curtime, plan_id, case_header)
                        db_res = sparrowDB.insert(sql)
                        if db_res:
                            collectLogs(loginfo='[%s]的执行结果插入数据库成功！' % (item,), lever='info',logger='waysToRun')
                        else:
                            temSql = '''INSERT INTO case_run_res(res_case_id,wheel_no,res_case_sign,res_group_id,res_case_path,res_case_parm,res_status,res_http_code,expect_res,res_detail,cost_time,run_type,create_by,update_by,create_at,update_at,res_plan_id,res_case_header) 
                                 VALUES (%d,%s,%s,%d,%s,%s,%d,%d,%s,%s,%d,%d,%s,%s,%s,%s,%d,%s)''' % (item[0], wheel_no,case_sign, groupId, resPath, resParam, runCode, httpCode, expect_res, '结果入库失败', duration, 2, user, user, curtime, curtime, plan_id, case_header)
                            temRes = sparrowDB.insert(temSql)
                            if temRes:
                                collectLogs(loginfo='[%s]的执行结果插入数据库成功，但是response入库失败' % (item,), lever='info', logger='waysToRun')
                            else:
                                collectLogs(loginfo='[%s]的执行结果插入数据库失败，失败的insert语句：%s' % (item, sql), lever='warning', logger='waysToRun')
                    except:
                        temSql2 = '''INSERT INTO case_run_res(res_case_id,wheel_no,res_case_sign,res_group_id,res_case_path,res_case_parm,res_status,res_http_code,expect_res,res_detail,cost_time,run_type,create_by,update_by,create_at,update_at,res_plan_id,res_case_header) 
                                VALUES (%d,%s,%s,%d,%s,%s,%d,%d,%s,%s,%d,%d,%s,%s,%s,%s,%d,%s)''' % (item[0], wheel_no, case_sign, groupId, resPath, resParam, runCode, httpCode, expect_res, '结果入库异常', duration, 2, user, user, curtime, curtime, plan_id, case_header)
                        temRes2 = sparrowDB.insert(temSql2)
                        if temRes2:
                            collectLogs(loginfo='[%s]的执行结果插入数据库成功，但是response入库失败' % (item,), lever='info', logger='waysToRun')
                        else:
                            collectLogs(loginfo='[%s]的执行结果插入数据库遇到异常，原因：%s' % (item, traceback.format_exc()), lever='error', logger='waysToRun')
                runCaseWay -= 1

                # 结果统计数据处理
                summary['成功用例'] = countSuccess
                summary['未执行'] = summary['用例总数'] - countSuccess - countFailed
                summary['失败用例'] = countFailed

                # 执行结果统计入库
                summary_time = "'" + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "'"
                try:
                    summary_sql = '''INSERT INTO case_run_res_summary(s_plan_id,s_plan_name,total_count,succ_count,fail_count,other_count,run_type,create_at) 
                                     VALUES (%d,%s,%d,%d,%d,%d,%d,%s)''' % (plan_id,s_plan_name,summary['用例总数'],summary['成功用例'],summary['失败用例'],summary['未执行'],2,summary_time)
                    db_res = sparrowDB.insert(summary_sql)
                    if db_res:
                        collectLogs(loginfo='结果统计插入数据库成功！', lever='info', logger='waysToRun')
                    else:
                        collectLogs(loginfo='结果统计插入数据库失败，插入结果为[%s]，失败的insert语句：%s' % (str(db_res), summary_sql), lever='info', logger='waysToRun')
                except:
                    collectLogs(loginfo='结果统计插入数据库遇到异常，原因：%s' % (traceback.format_exc()), lever='error', logger='waysToRun')

                # 组装钉钉报警消息，失败报警
                if config.isDingtalk and errorCasesMsgList:
                    collectLogs(loginfo='有失败用例，需要发送消息提醒，开始发送钉钉报警消息...', logger='waysToRun')
                    errorCaseMsg = ''
                    for caseItem in errorCasesMsgList:
                        toCaseUrl = config.MESSAGE_URL_SPARROW + str(caseItem[1])
                        if caseItem[4] == 200:
                            httpCodeColor = '<font color=#32CD32>200</font>'
                        else:
                            httpCodeColor = '<font color=#FF0000>' + str(caseItem[4]) + '</font>'
                        errorCaseMsg = errorCaseMsg + "【第" + str(errorCasesMsgList.index(caseItem) + 1) + "个】[" + caseItem[0] + "](" + toCaseUrl + ") \n> #### 预期结果：" + caseItem[2] + " \n> #### 匹配结果：" + caseItem[3] + "，httpCode：" + httpCodeColor + " \n> #### [" + caseItem[5] + "](" + caseItem[5] + ") \n> #### 响应信息：" + caseItem[6] + " \n\n> "
                    sendRes = sendDingTalkMsg_sparrow(DINGTALK_URL, summary, errorCaseMsg)
                    if sendRes["code"] == 1:
                        collectLogs(loginfo='钉钉报警消息发送成功！', logger='waysToRun')
                    else:
                        collectLogs(loginfo='钉钉报警消息发送失败，发送响应：%s' % (sendRes,), lever='warning', logger='waysToRun')

                # 组装钉钉报警消息，响应时间超过阀值预警
                if config.IS_SEND_WARN_MSG and overWarnTimeLimitList:
                    summaryMsg = "任务【"+ plan_name +"】中有 "+ str(len(overWarnTimeLimitList)) +" 个用例响应时间超过 "+ str(config.MIN_LIMIT_WARNTIME_YELLOW) +" 秒，请及时确认服务是否正常，详细信息如下："
                    warnCaseMsg = ''
                    for warnItem in overWarnTimeLimitList:
                        toWarnCaseUrl = config.MESSAGE_URL_SPARROW + str(warnItem[1])
                        warnCaseMsg = warnCaseMsg + "【第" + str(overWarnTimeLimitList.index(warnItem) + 1) + "个】["+ warnItem[0] +"]("+ toWarnCaseUrl +") \n> #### 响应时间：" + warnItem[2] + " 秒 \n> #### URL：" + warnItem[3] + " \n\n> "
                    sendWarnMsgRes = sendDingTalkWarnMsg_sparrow(DINGTALK_URL_WARN, summaryMsg, warnCaseMsg)
                    if sendWarnMsgRes["code"] == 1:
                        collectLogs(loginfo='钉钉预警消息发送成功！', logger='waysToRun')
                    else:
                        collectLogs(loginfo='钉钉预警消息发送失败，发送响应：%s' % (sendWarnMsgRes,), lever='warning', logger='waysToRun')

                if runCaseWay == 0:
                    break
                collectLogs('第 %d 次执行结束，%d秒后继续执行...(剩余 %d 次)' % (tem - runCaseWay, waitTime, runCaseWay), logger='waysToRun')
                time.sleep(waitTime)
            end = time.time()
            duration = int(end - start)
            collectLogs('本轮计划执行结束【共 %d 次】，耗时 %d 分钟 %d 秒' % (tem - runCaseWay, duration / 60, duration % 60), logger='waysToRun')

        # 按指定分钟数执行
        elif runCaseWay > 0 and runCaseWay_01 == '分钟':
            wheel_no = "'" + generateNums(32, 1) + "'"
            sql1 = "select * from case_run_res where wheel_no = %s" % (wheel_no,)
            check_wheel_no = sparrowDB.get_one(sql1)
            if check_wheel_no:
                wheel_no = "'" + generateNums(33, 1) + "'"

            countSuccess = 0
            countFailed = 0
            errorCasesMsgList = []
            overWarnTimeLimitList = []
            start1 = time.time()
            for item in case:
                errorCasesMsgList_tem = []
                overWarnTimeLimitList_tem = []
                curtime = "'" + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "'"
                user = "'" + '系统更新' + "'"
                try:
                    res = runOneCase(case=item)

                    response = response_send = res['data']['runRes']
                    if len(response) > MAX_RES_LENTH:
                        response = response[:MAX_RES_LENTH]
                    if len(response_send) > SEND_MAX_RES:
                        response_send = response_send[:SEND_MAX_RES]
                    response = "'" + pymysql.escape_string(response) + "'"
                    resPath = "'" + res['data']['casePath'] + "'"
                    resParam = "'" + pymysql.escape_string(res['data']['caseParam']) + "'"
                    expect_res = "'" + res['data']['expect_res'] + "'"
                    case_sign = "'" + item[2] + "'"
                    case_header = "'" + item[7] + "'"
                    runCode = res['runCode']
                    httpCode = res['data']['httpCode']
                    duration = int(res['data']['duration'][:-2])
                    duration_sec = duration / 1000
                    if runCode == 1:
                        countSuccess += 1
                    if runCode == 9:
                        countFailed += 1
                        errorCasesMsgList_tem.append(item[1])
                        errorCasesMsgList_tem.append(item[0])
                        errorCasesMsgList_tem.append(item[6])
                        errorCasesMsgList_tem.append('<font color=#FF0000>失败</font>')
                        errorCasesMsgList_tem.append(httpCode)
                        errorCasesMsgList_tem.append(item[3])
                        errorCasesMsgList_tem.append(response_send)
                        errorCasesMsgList.append(errorCasesMsgList_tem)
                    if duration_sec >= config.MIN_LIMIT_WARNTIME_YELLOW:
                        duration_sec_color = '<font color=#FFD700>' + str(duration_sec) + '</font>'
                        overWarnTimeLimitList_tem.append(item[1])
                        overWarnTimeLimitList_tem.append(item[0])
                        if duration_sec >= config.MIN_LIMIT_WARNTIME_RED:
                            duration_sec_color = '<font color=#FF0000>'+str(duration_sec)+'</font>'
                        overWarnTimeLimitList_tem.append(duration_sec_color)
                        overWarnTimeLimitList_tem.append(item[3])
                        overWarnTimeLimitList.append(overWarnTimeLimitList_tem)
                except:
                    collectLogs(loginfo='执行[%s]遇到异常，原因：%s' % (item, traceback.format_exc()), lever='error',
                                logger='waysToRun')
                    response = "'" + '遇到异常，未执行' + "'"
                    resPath = "'" + '遇到异常，未执行' + "'"
                    resParam = "'" + '遇到异常，未执行' + "'"
                    expect_res = "'" + '遇到异常，未执行' + "'"
                try:
                    # 将结果插入数据库
                    sql = '''INSERT INTO case_run_res(res_case_id,wheel_no,res_case_sign,res_group_id,res_case_path,res_case_parm,res_status,res_http_code,expect_res,res_detail,cost_time,run_type,create_by,update_by,create_at,update_at,res_plan_id,res_case_header) 
                             VALUES (%d,%s,%s,%d,%s,%s,%d,%d,%s,%s,%d,%d,%s,%s,%s,%s,%d,%s)''' % (item[0], wheel_no,case_sign, groupId, resPath, resParam, runCode, httpCode, expect_res, response, duration, 2, user, user, curtime, curtime, plan_id, case_header)
                    db_res = sparrowDB.insert(sql)
                    if db_res:
                        collectLogs(loginfo='[%s]的执行结果插入数据库成功！' % (item,), lever='info',logger='waysToRun')
                    else:
                        temSql = '''INSERT INTO case_run_res(res_case_id,wheel_no,res_case_sign,res_group_id,res_case_path,res_case_parm,res_status,res_http_code,expect_res,res_detail,cost_time,run_type,create_by,update_by,create_at,update_at,res_plan_id,res_case_header) 
                             VALUES (%d,%s,%s,%d,%s,%s,%d,%d,%s,%s,%d,%d,%s,%s,%s,%s,%d,%s)''' % (item[0], wheel_no,case_sign, groupId, resPath, resParam, runCode, httpCode, expect_res, '结果入库失败', duration, 2, user, user, curtime, curtime, plan_id, case_header)
                        temRes = sparrowDB.insert(temSql)
                        if temRes:
                            collectLogs(loginfo='[%s]的执行结果插入数据库成功，但是response入库失败' % (item, ), lever='info', logger='waysToRun')
                        else:
                            collectLogs(loginfo='[%s]的执行结果插入数据库失败，插入结果为[%s]，失败的insert语句：%s' % (item, str(db_res), sql), lever='info', logger='waysToRun')
                except:
                    temSql2 = '''INSERT INTO case_run_res(res_case_id,wheel_no,res_case_sign,res_group_id,res_case_path,res_case_parm,res_status,res_http_code,expect_res,res_detail,cost_time,run_type,create_by,update_by,create_at,update_at,res_plan_id,res_case_header) 
                           VALUES (%d,%s,%s,%d,%s,%s,%d,%d,%s,%s,%d,%d,%s,%s,%s,%s,%d,%s)''' % (item[0], wheel_no, case_sign, groupId, resPath, resParam, runCode, httpCode, expect_res, '结果入库异常', duration, 2, user, user, curtime, curtime, plan_id, case_header)
                    temRes2 = sparrowDB.insert(temSql2)
                    if temRes2:
                        collectLogs(loginfo='[%s]的执行结果插入数据库成功，但是response入库失败' % (item, ), lever='info', logger='waysToRun')
                    else:
                        collectLogs(loginfo='[%s]的执行结果插入数据库遇到异常，原因：%s' % (item, traceback.format_exc()), lever='error', logger='waysToRun')
            end1 = time.time()
            duration = end1 - start1
            if duration < 1:
                collectLogs('本轮计划【%s】执行结束，耗时 %.3f 秒' % (plan_name, duration), logger='waysToRun')
            else:
                duration = round(duration)
                collectLogs('本轮计划【%s】执行结束，耗时 %d 分钟 %d 秒' % (plan_name, duration / 60, duration % 60), logger='waysToRun')

            # 结果统计数据处理
            summary['成功用例'] = countSuccess
            summary['未执行'] = summary['用例总数'] - countSuccess - countFailed
            summary['失败用例'] = countFailed

            # 执行结果统计入库
            summary_time = "'" + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "'"
            try:
                summary_sql = '''INSERT INTO case_run_res_summary(s_plan_id,s_plan_name,total_count,succ_count,fail_count,other_count,run_type,create_at) 
                                 VALUES (%d,%s,%d,%d,%d,%d,%d,%s)''' % (plan_id, s_plan_name, summary['用例总数'], summary['成功用例'], summary['失败用例'], summary['未执行'], 2, summary_time)
                db_res = sparrowDB.insert(summary_sql)
                if db_res:
                    collectLogs(loginfo='结果统计插入数据库成功！', lever='info', logger='waysToRun')
                else:
                    collectLogs(loginfo='结果统计插入数据库失败，插入结果为[%s]，失败的insert语句：%s' % (str(db_res), summary_sql), lever='info', logger='waysToRun')
            except:
                collectLogs(loginfo='结果统计插入数据库遇到异常，原因：%s' % (traceback.format_exc()), lever='error', logger='waysToRun')

            # 组装钉钉报警消息
            if config.isDingtalk and errorCasesMsgList:
                collectLogs(loginfo='有失败用例，需要发送消息提醒，开始发送钉钉报警消息...', logger='waysToRun')
                errorCaseMsg = ''
                for caseItem in errorCasesMsgList:
                    toCaseUrl = config.MESSAGE_URL_SPARROW + str(caseItem[1])
                    if caseItem[4] == 200:
                        httpCodeColor = '<font color=#32CD32>200</font>'
                    else:
                        httpCodeColor = '<font color=#FF0000>' + str(caseItem[4]) + '</font>'
                    errorCaseMsg = errorCaseMsg + "【第" + str(
                        errorCasesMsgList.index(caseItem) + 1) + "个】[" + caseItem[0] + "](" + toCaseUrl + ") \n> #### 预期结果：" + caseItem[2] + " \n> #### 匹配结果：" + caseItem[3] + "，httpCode：" + httpCodeColor + " \n> #### [" + caseItem[5] + "](" + caseItem[5] + ") \n> #### 响应信息：" + caseItem[6] + " \n\n> "
                sendRes = sendDingTalkMsg_sparrow(DINGTALK_URL, summary, errorCaseMsg)
                if sendRes["code"] == 1:
                    collectLogs(loginfo='钉钉报警消息发送成功！', logger='waysToRun')
                else:
                    collectLogs(loginfo='钉钉报警消息发送失败，发送响应：%s' % (sendRes,), lever='warning', logger='waysToRun')

            # 组装钉钉报警消息，响应时间超过阀值预警
            if config.IS_SEND_WARN_MSG and overWarnTimeLimitList:
                summaryMsg = "任务【" + plan_name + "】中有 " + str(
                    len(overWarnTimeLimitList)) + " 个用例响应时间超过 " + str(
                    config.MIN_LIMIT_WARNTIME_YELLOW) + " 秒，请及时确认服务是否正常，详细信息如下："
                warnCaseMsg = ''
                for warnItem in overWarnTimeLimitList:
                    toWarnCaseUrl = config.MESSAGE_URL_SPARROW + str(warnItem[1])
                    warnCaseMsg = warnCaseMsg + "【第" + str(overWarnTimeLimitList.index(warnItem) + 1) + "个】[" + warnItem[0] + "](" + toWarnCaseUrl + ") \n> #### 响应时间：" + warnItem[2] + " 秒 \n> #### URL：" + warnItem[3] + " \n\n> "
                sendWarnMsgRes = sendDingTalkWarnMsg_sparrow(DINGTALK_URL_WARN, summaryMsg, warnCaseMsg)
                if sendWarnMsgRes["code"] == 1:
                    collectLogs(loginfo='钉钉预警消息发送成功！', logger='waysToRun')
                else:
                    collectLogs(loginfo='钉钉预警消息发送失败，发送响应：%s' % (sendWarnMsgRes,), lever='warning',logger='waysToRun')

        # 都不符合
        else:
            collectLogs(loginfo='参数设置有误！（case=%s，runCaseWay=%s，runCaseWay_01=%s，waitTime=%s）' %(str(case), str(runCaseWay), str(runCaseWay_01), str(waitTime)), logger='waysToRun')
    except Exception:
        collectLogs(loginfo='执行遇到异常，原因：%s' % traceback.format_exc(), lever='error', logger='waysToRun')
